#!/usr/bin/env python
from inspect import getmodule
from string import zfill

# Iroad sim - running lights algorith simulator
# Copyright (C) 2010 Laurynas Riliskis <laurynas.riliskis@gmail.com>
#
# This file is part of IroadSim.
#
# IroadSim is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# IroadSimis distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with IroadSim.  If not, see <http://www.gnu.org/licenses/>

"""
you only need to implement the algorithm in Node
Assume static allocated intervals
OBS: make sure that fps are in sync with Node timer events.
this can be the reason that after time x node blinking goes out of sync
"""
from pyglet import  clock
from iroad import NodeImage

"""
Variables used for simulator 
"""
NUMBER_OF_NODES = 50 #number of nodes in the simulation
win_width = 600      #width of animation window
win_height= 600      #height of animation window 

"""
Define your variables here
"""

g_Flags = int(('0'+zfill((bin(13).replace('0b','')),6)+zfill((bin(9).replace('0b','')),6)),2)

class Node (NodeImage):

    #Variables
    led = False
    __Ticks = int(1)
    
    #constants
    __Nodes = int(NUMBER_OF_NODES)
    
    #test
    def TestDef(self):
        return 0
    
    def __init__(self, id, **kwargs):
        #init
        self.id=id

        #Cheking Station integrity
                
        #nome image creator
        NodeImage.__init__(self, **kwargs)
        
        #Calculate pivots
        Pivots = self.__calcPivots()

        #Setting initialy
        if self.id in Pivots:
            self.turnLedOn()

        #Setup Timer
        clock.schedule_interval(self.toggleLed, 0.5)
    
    #Calculate direction CC (clockwise) or CCW
    def __calcDirection(self,data):
        return bool(data >> 12)
    
    #Calculating tail length
    def __calcTail(self,data):
        return data & int('0000000111111',2) 
    
    #Calculating space between nodes
    def __calcSpace(self,data):
        return (data & int('0111111000000',2)) >> 6
    
    #Calculate pivots
    def __calcPivots(self):
        #Getting Variables from base station
        global g_Flags
        
        Nodes = self.__Nodes
        Lights = self.__calcSpace(g_Flags)
        
        #Calculating pivots
        Pivots = range(1,Nodes+1,Lights)
        if self.id in Pivots:
            print '['+str(self.id)+'][Pivots]'+str(Pivots)
        
        #Adjusting pivots
        Pivots2 = Pivots
        if(Nodes % Lights) > 0:
            Module = (Nodes % Lights)
            a = 0
            while Module > 0:
                Pivots[len(Pivots)-1-a] += 1
                Module -= 1

                if Module > 0:
                    for x in range(a,len(Pivots)):
                        Pivots[x] += 1
                    Module -= 1;    
                a += 1
                
        if self.id in Pivots2:
            print '['+str(self.id)+'][Pivots]'+str(Pivots)                
                    
                
        """            
        if (Nodes % Lights) > 0:
            Module = (Nodes % Lights)
            Pivots.reverse()
            
            for x in range(len(Pivots)):
                Pivots[x] += Module
                if Module > 0:
                    Module -= 1
        """
        return Pivots
    
    #return state of the led
    def ledState(self):
        return self.led
         
    #set the led status on    
    def turnLedOn(self):
        self.led=True
    
    #set led status off    
    def turnLedOff(self):    
        self.led=False

    #toggle led
    def toggleLed(self, interval):
        #Globals
        global g_Flags
        
        Nodes = self.__Nodes
        Lights = self.__calcSpace(g_Flags)
        
        #Storing the time
        self.__Ticks += 1
        
        #Recognize the cycle
        if self.__Ticks == Nodes:
            self.__Ticks = 1   
        #Calculating pivots
        Pivots = self.__calcPivots()
        
        #Setting pivots
        for x in range(len(Pivots)):
            Pivots[x] += self.__Ticks
            if Pivots[x] > Nodes:
                Pivots[x] -= Nodes
        #Pivots = list(set(Pivots))
        
        #Setting the led
        if self.id in Pivots:
            self.turnLedOn()
        else:
            self.turnLedOff()

    #return led    
    def getLed(self):
        return self.led